//
// Copyright (c) 2004-2005 BroadVision, Inc. All rights reserved.
//
// This software is copyrighted.  Under the copyright laws, this software
// may not be copied, in whole or in part, without prior written consent
// of BroadVision, Inc. or its assignees.  This software is provided under
// the terms of a license between BroadVision and the recipient, and its
// use is subject to the terms of that license.
//
// This software may be protected by one or more U.S. and International
// patents.  Certain applications of BroadVision One-To-One software are
// covered by U.S. patent 5,710,887.
//
// TRADEMARKS: BroadVision and BroadVision One-To-One are registered
// trademarks of BroadVision, Inc., in the United States and the European
// Community, and are trademarks of BroadVision, Inc., in other
// countries.  The BroadVision logo, is a trademark of BroadVision, Inc.,
// in the United States and other countries. Additionally, IONA and Orbix
// are trademarks of IONA Technologies, Ltd.  RSA, MD5, and RC2 are
// trademarks of RSA Data Security, Inc.
//

package com.broadvision.manage.common.tools.action.inbox;

import java.io.ByteArrayInputStream;
import java.util.List;
import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.broadvision.data.common.TableData;
import com.broadvision.data.common.RowData;
import com.broadvision.data.common.DataValue;
import com.broadvision.alerts.client.AlertManager;
import com.broadvision.alerts.exceptions.AlertException;
import com.broadvision.jdom.Element;
import com.broadvision.jdom.Document;
import com.broadvision.jdom.input.SAXBuilder;
import com.broadvision.visitor.client.Visitor;
import com.broadvision.web.util.ViewDynaBean;
import com.broadvision.manage.tools.action.BaseAction;

/**
 * View an alert.
 */
public class AlertViewAction extends BaseAction {

  public static final String VIEW_BEAN_NAME = "mtAlertView";

  /**
   * Implements the action for viewing an alert.
   * <p> <p>
   * @param mapping <code>ActionMapping</code> object used to select this instance
   * @param form Optional <code>ActionForm</code> bean for this request (if any)
   * @param request <code>HttpServletRequest</code> object to process
   * @param response <code>HttpServletResponse</code> object to process
   * <p> <p>
   * @return <code>ActionForward</code> instance describing where and how
   * control should be forwarded, or null if the response has already been completed
   * <p> <p>
   * @throws Exception if an error occurs
   */
  public ActionForward processExecute(ActionMapping mapping,
                                      ActionForm form,
                                      HttpServletRequest request,
                                      HttpServletResponse response)
                               throws Exception {
    Visitor visitor = getVisitor(request);

    String alertName = request.getParameter("alertName");
    String messageId = request.getParameter("messageId");
    int msgId = Integer.parseInt(messageId);

    String[] columns = new String[9];
    columns[0] = "ALERT_NAME";
    columns[1] = "MESSAGE_ID";
    columns[2] = "CREATION_DATE";
    columns[3] = "DATE_READ";
    columns[4] = "FROM_WHOM";
    columns[5] = "SUBJECT";
    columns[6] = "ALERT_MESSAGE";
    columns[7] = "JOB_ID";
    columns[8] = "ALERT_CAT";

    AlertManager alertMgr = new AlertManager();
    TableData msg =
      alertMgr.getInboxMessage(visitor.getId(), alertName, msgId, columns);
    RowData row = msg.getRow(0);

    ViewDynaBean view = new ViewDynaBean(VIEW_BEAN_NAME, mapping);
    request.setAttribute(VIEW_BEAN_NAME, view);

    DataValue value = row.getValue(columns[0]);
    PropertyUtils.setSimpleProperty(view, "alertName", value.getString());
    value = row.getValue(columns[1]);
    PropertyUtils.setSimpleProperty(view, "messageId", value.getString());
    value = row.getValue(columns[2]);
    PropertyUtils.setSimpleProperty(view, "creationDate", value.getDateTime());
    value = row.getValue(columns[3]);
    PropertyUtils.setSimpleProperty(view, "dateRead", value.getDateTime());
    value = row.getValue(columns[4]);
    PropertyUtils.setSimpleProperty(view, "from", value.getString());
    value = row.getValue(columns[5]);
    PropertyUtils.setSimpleProperty(view, "subject", value.getString());
    value = row.getValue(columns[6]);
    String message = value.getString();
    value = row.getValue(columns[7]);
    PropertyUtils.setSimpleProperty(view, "jobId", value.getString());
    value = row.getValue(columns[8]);
    int alertCat = value.getInt();

    if (alertCat == 1) { // Task notification
      String[] elements = parseMessage(message);
      message = elements[0];
    }
    else if (alertCat == 2) { // Meeting notification
      String[] elements = parseMessage(message);
      message = elements[0];
    }
    else if (alertCat == 3) { // Participant notification
      String[] elements = parseMessage(message);
      message = elements[0];
    }
    PropertyUtils.setSimpleProperty(view, "alertMessage", message);

    return mapping.findForward("success");
  }

  /**
   * The alert messages generated by collaboration space activities
   * is stored in the database as a XML string.
   * Parse the message to extract the individual entities
   *
   * @param rawMessage
   *
   * @return A string array that contains the individual entities
   *
   * @throws AlertException
   */
  private String[] parseMessage(String rawMessage) throws AlertException {
    try {
      SAXBuilder builder = new SAXBuilder();

      ByteArrayInputStream inputStream =
        new ByteArrayInputStream(rawMessage.getBytes("UTF-8"));

      Document doc = builder.build(inputStream);

      Element root = doc.getRootElement();

      if (root.getName().equals("ALERT_MESSAGE")) {
        String[] messageComponents = new String[4];

        List entities = root.getChildren();
        Iterator it = entities.iterator();

        while (it.hasNext()) {
          Element entity = (Element) it.next();
          if (entity.getName().equals("MESSAGE")) {
            messageComponents[0] = new String(entity.getText());
          }
          else if (entity.getName().equals("MICROSITE_ID")) {
            messageComponents[1] = new String(entity.getText());
          }
          else if (entity.getName().equals("PHASE_ID")) {
            messageComponents[2] = new String(entity.getText());
          }
          else if (
            entity.getName().equals("TASK_ID")
              || entity.getName().equals("MEETING_ID")) {
            messageComponents[3] = new String(entity.getText());
          }
        }
        return messageComponents;
      }
    }
    catch (Exception ex) {
      throw new AlertException("Unable to parse alert XML message");
    }

    return null;
  }
}
